use std::{thread, time::Duration};
use std::process::{Command, Stdio};


struct SystemMonitor {
    interval: Duration,
}
impl SystemMonitor {
    fn new(interval_secs: u64) -> Self {
        SystemMonitor { interval: Duration::from_secs(interval_secs), }
    }
    fn start_monitor(&self) -> Result<(), Box<dyn std::error::Error>> {
        loop {
            println!("=========System Statistics=========");
            //     CPU使用率(Linux)
            let ps = Command::new("ps")
                .args(&["-eo", "pcpu,pid,comm"])
                .stdout(Stdio::piped())
                .spawn()?;
            // "ps -eo pcpu,pid,comm|sort -rk 1|head -n 10"
            let sort = Command::new("sort")
                .args(&["-rk","1"])
                .stdin(Stdio::from(ps.stdout.unwrap()))
                .stdout(Stdio::piped())
                .spawn()?;
            let head = Command::new("head")
                .args(&["-n", "10"])
                .stdin(Stdio::from(sort.stdout.unwrap()))
                .spawn()?;
            let cpu = head.wait_with_output()?;
        //     内存使用率(linux)
            let memory = Command::new("vmstat")
                .arg("-a")
                .output()?;
        //     磁盘使用率
            let disk = Command::new("df").args(["-h"]).output()?;
            self.display_stats(&cpu.stdout, &memory.stdout, &disk.stdout);
            println!("========================================================================");
            thread::sleep(self.interval);
        }
    }

    fn display_stats(&self, cpu: &[u8], memory: &[u8], disk: &[u8]) {
        println!("{}\n{}\n{}", String::from_utf8_lossy(cpu),String::from_utf8_lossy(memory),String::from_utf8_lossy(disk));
    }
}
// 系统监控工具
fn main() {
    let monitor = SystemMonitor::new(5); //每5秒监控一次
    if let Err(e) = monitor.start_monitor() {
        eprintln!("Error: {}", e);
    }
}
